<!doctype html>
<html>
 <head> 
  <script src="/nacl-fast.min.js"></script>
  <script src="/msgpack.js"></script>
 <script src="/uuid.js"></script>
  <script src="/nacl-cert.js"></script>
  <script src="/sws.js"></script>

  <script type="text/javascript">
   function SecureWebSocket() {
	if ("sws" in window) {
		var kp = sws.keyPair();
		var ws = new sws.SecureWebSocket('ws://localhost:6188/wspp', 
				{
						version: 1,
						myPublicKey: kp.publicKey,
						mySecretKey: kp.secretKey
				});

		ws.onopen = function(){
			console.log('secure ws connected');

			ws.onmessage = function(msg){
				var data = msg.data;
				var type = msg.type;

				if (type === 'Binary') {
					var message = msgpack.decode(data);
					console.log('client message:'+message);
					///alert('client message:'+message);

					// append log
					document.getElementById("log").value += '\n'+message;
				} else {
					console.log('Not support String message');
				}
			};

			setInterval(function(){
				ws.send(msgpack.encode('Hello,Am Tom@'+Date.now()));
			}, 2000);
		};
		ws.on('warn', function(warn){
			console.log('warn:'+warn);
		});
		ws.onclose = function() { 
			// SecureWebSocket is closed.
			console.log("Connection is closed..."); 
		};

		// V2 with NACL CERT support
		var bkp = sws.keyPair();
		// prepare reqdesc
		var reqdesc = {
				version: '1.0',
				type: 'ca',
				tte: new Date('2016-01-01').getTime(),
				publickey: sws.Uint8ToArray(bkp.publicKey),
				names: ['51dese.com','ruyier.com','localhost'],
				ips: ['127.0.0.1']
		};
		var bcert = naclcert.generate(reqdesc, naclcert.testCA.secretkey, naclcert.testCA.cert);

		var ws2 = new sws.SecureWebSocket('ws://localhost:6188/wspp/v2', 
				{
						version: 2,
						ca: naclcert.testCA.cert,
						cert: bcert,

						myPublicKey: bkp.publicKey,
						mySecretKey: bkp.secretKey
				});

		ws2.onopen = function(){
			console.log('secure ws connected V2');

			ws2.onmessage = function(msg){
				var data = msg.data;
				var type = msg.type;

				if (type === 'Binary') {
					var message = msgpack.decode(data);
					console.log('client message V2:'+message);
					///alert('client message:'+message);

					// append log
					document.getElementById("log").value += '\nV2 '+message;
				} else {
					console.log('Not support String message');
				}
			};

			setInterval(function(){
				ws2.send(msgpack.encode('V2 Hello,Am Tom@'+Date.now()));
			}, 2000);
		};
		ws2.on('warn', function(warn){
			console.log('warn:'+warn);
		});
		ws2.onclose = function() { 
			// SecureWebSocket is closed.
			console.log("V2 Connection is closed..."); 
		};

	} else {
		// The browser doesn't support SecureWebSocket
		alert("SecureWebSocket NOT supported by your Browser!");
	  }
     }
	</script>
 </head>

 <body> 
  <div id="sws">
   <a href="javascript:SecureWebSocket()">Run SecureWebSocket</a>
  </div>

  <textarea id="log" rows="20" cols="50">
  </textarea >
	
 </body>
</html>